package blueq.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import blueq.dao.mongodb.impl.MongoDBDaoImpl;
import blueq.entity.mongo.AppInfo;
import blueq.util.JsonParser;
import blueq.util.ResponseWriter;



@Controller
public class AppRequestController {
	@Resource(name = "mongoDbDao")
	private MongoDBDaoImpl mongoDao;
	
	public MongoDBDaoImpl getMongoDao() {
		return mongoDao;
	}

	public void setMongoDao(MongoDBDaoImpl mongoDao) {
		this.mongoDao = mongoDao;
	}

	/**
	 * 上传图片并返回搜索结果
	 * @param file
	 * @param request
	 */
	@RequestMapping("/Search")
	public void uploadAndSearch(@RequestParam("image") MultipartFile file, HttpServletRequest request) {
		//获取文件保存路径
		String path = request.getSession().getServletContext().getRealPath("upload");
		
		//获取文件名
		String fileName = file.getOriginalFilename();
		File target = new File(path, fileName);
		if(!target.exists()) {
			target.mkdirs();
		}
		System.out.println(path);
		try {
			//保存文件
			file.transferTo(target);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//do someting
	}
	
	/**
	 * 获取推荐app列表
	 * @param response
	 */
	@RequestMapping("/SearchRecommend")
	public @ResponseBody String searchRecommend(HttpServletResponse response) {
		List<AppInfo> list = mongoDao
				.getAllObjects(AppInfo.class, "data_table");
		List<AppInfo> items = new ArrayList<AppInfo>();
		for (int i = 0; i < 50 && !list.isEmpty(); i++) {
			items.add(list.get(i));
		}
		String json = JsonParser.parseResult(items);
		System.out.println(json);
		//ResponseWriter.responseText(response, json);
		return json;
	}
	
}
